package api.action;

import api.model.ApiAuthinfo;
import api.service.ApiAuthinfoService;
import m.common.action.ActionMeta;
import m.common.action.VuePageResult;
import m.common.action.VueResult;
import m.common.model.util.ModelQueryList;
import m.html.VueFormResult;
import m.html.VueListResult;
import m.html.element.Element;
import m.html.element.attr.Align;
import m.html.element.attr.ButtonType;
import m.html.form.*;
import m.html.list.ListButton;
import m.html.list.ListElement;
import m.html.list.SuccessMethod;
import m.system.cache.CacheUtil;
import m.system.util.GenerateID;
import m.system.util.JSONMessage;
import m.system.util.StringUtil;
import manage.action.StatusAction;

@ActionMeta(name="api/apiAuthinfo")
public class ApiAuthinfoAction extends StatusAction {
    private ApiAuthinfo model;

    public JSONMessage doSave() throws Exception {
        systemLog("鉴权","保存鉴权信息");
        verifyAdminOperPower(getStatusPower());
        String msg=getService(ApiAuthinfoService.class).save(model);
        return new JSONMessage(0,msg)
                .push("model", model);
    }
    public VueResult toEdit() throws Exception {
        verifyMenu("A2111");
        verifyAdminOperPower(getStatusPower());
        if(null!=model&&!StringUtil.isSpace(model.getAuthId())){
            model=getService(ApiAuthinfoService.class).get(model.getAuthId());
        }else {
            model=new ApiAuthinfo();
            model.setAdmin(getSessionAdmin());
            model.setOrg(getSessionOrgGroup());
            model.setAuthId(GenerateID.upsetKey(GenerateID.generatePrimaryKey()).toLowerCase());
            model.setAuthKey(
                GenerateID.upsetKey(GenerateID.upsetKey(
                    GenerateID.upsetKey(GenerateID.generatePrimaryKey())
                    +GenerateID.upsetKey(GenerateID.tempKey())
                )).toLowerCase()
            );
            model.setAuthTime("10");
            model.setType("B");
        }
        ModelForm form = new ModelForm("鉴权信息");
        form.addItem(
            FormInput.input("名称", "model.name").setPlaceholder("请输入名称"),
            FormInput.input("描述", "model.description").setPlaceholder("请输入描述").setSpan(2),
            FormInput.input("鉴权id", "model.authId").setPlaceholder("请输入鉴权id"),
            FormInput.input("鉴权key", "model.authKey").setPlaceholder("请输入鉴权key").setSpan(2),
            FormInput.radio("类型", "model.type", "api.model.ApiAuthinfo!type"),
            FormInput.radio("鉴权误差", "model.authTime", "api.model.ApiAuthinfo!authTime").setSpan(2),
            FormInput.select("登录人","model.admin.oid","manage.model.AdminLogin").setPlaceholder("请选择登录人"),
            FormInput.selectTree("登录部门", "model.org.oid","manage.model.AdminGroup:C;;").setPlaceholder("请登录部门").setSpan(2),
            FormElement.add(
                Element.tag("a-alert").A("message","使用鉴权：在请求是head添加Authorization").A("description","设置成：(标识:auth)空格authid空格timelong空格to32Md5(timelong+authid+authkey)")
            )
        )
        .addData("model",model)
        .addButton(
            FormButton.pri("保存","doSave")
        )
        .addMethod(
            FormEvent.backFlag,
            FormEvent.doJson("doSave",actionUrl("doSave"),"{model:this.model}")
                .success("backFlag")
        );
        VueFormResult result=new VueFormResult();
        return result.addForm(form);
    }
    public VueResult toApiAuthinfoInterList() throws Exception {
        model=getService(ApiAuthinfoService.class).get(model.getAuthId());
        return new VuePageResult("page/base/api/auth/apiAuthinfoInterList.js")
                .addParam("model",model);
    }
    public VueResult apiAuthinfoList() throws Exception{
        verifyMenu("A2111");
        boolean power=hasAdminOperPower(getStatusPower());
        VueListResult result=getVueListResult("鉴权信息登记", ApiAuthinfo.class,actionUrl("apiAuthinfoList"));
        result.setSubTitle("可用通过鉴权信息访问系统接口，鉴权需要使用MD5加密，推荐后台访问使用该鉴权信息。");
        result.addCol(toIndexColumn());
        result.addCol(toTextColumn("名称", "name",true));
        result.addCol(toTextColumn("描述", "description",200,true));
        result.addCol(toTextColumn("登录人", "admin.realname",true));
        result.addCol(toTextColumn("登录机构", "org.name",true));
        result.addCol(toTextColumn("鉴权id", "authId",true));
        result.addCol(toTextColumn("鉴权key", "authKey",150,true));
        result.addCol(toTextColumn("鉴权误差", "authTime",true).setDictOption(ApiAuthinfo.class,"authTime"));
        result.addCol(toTextColumn("类型", "type",true).setDictOption(ApiAuthinfo.class,"type"));
        result.addCol(toStatusColumn(power,true));
        if(power) result.addCol(toSpaceColumn("操作",150,
            ListButton.modal("修改", ButtonType.PRIMARY,actionUrl("toEdit"),900, SuccessMethod.REFRESH)
                .addParam("model.authId","authId"),
                ListElement.test("record.type=='B'",
                    ListButton.page("接口", ButtonType.SUCCESS,actionUrl("toApiAuthinfoInterList"), SuccessMethod.REFRESH)
                        .addParam("model.authId","authId")
                )
        ).setFixed(Align.RIGHT));
        if(power) result.addButton(
                ListButton.modal("新增",ButtonType.PRIMARY,actionUrl("toEdit"),900,SuccessMethod.REFRESH)
        );
        return result;
    }

    @Override
    public void doRecoveryCallback() throws Exception {
        model= ModelQueryList.getModel(model,"authId");
        CacheUtil.clear(ApiAuthinfo.class,model.getAuthId());
    }

    @Override
    public void doDisableCallback() throws Exception {
        model= ModelQueryList.getModel(model,"authId");
        CacheUtil.clear(ApiAuthinfo.class,model.getAuthId());
    }

    @Override
    public ApiAuthinfo getModel() {
        return model;
    }

    @Override
    public String[] getStatusPower() {
        return new String[]{"manage_api_power"};
    }

    public void setModel(ApiAuthinfo model) {
        this.model = model;
    }
}
